package com.kdgc.power.fw.service;

import com.kdgc.power.fw.bean.SystemConfig;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SqlId;
import org.beetl.sql.core.page.DefaultPageRequest;
import org.beetl.sql.core.page.PageRequest;
import org.beetl.sql.core.page.PageResult;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service("BeetSqlHelp")
public class BeetSqlHelp {
    @Resource
    @Qualifier(SystemConfig.MAIN_SQL_MANAGER)
    private SQLManager sqlManager;

    public List<Map<String, Object>> getMapList(String sqlId, Map<String, Object> para) {
        SqlId sql = SqlId.of(sqlId);
        @SuppressWarnings("unchecked")
        Class<Map<String, Object>> clazz = (Class<Map<String, Object>>) (Class<?>) Map.class;
        return sqlManager.select(sql, clazz, para);
    }

    public <T> List<T> getList(String sqlId, Map<String, Object> paras, Class<T> cls) {
        return sqlManager.select(SqlId.of(sqlId), cls, paras);
    }

    public PageResult<Map<String, Object>> getPage(SqlId sqlId, Map<String, Object> paras, Integer page, Integer rows) {
        PageRequest <?>pageRequest = DefaultPageRequest.of(page, rows);
        @SuppressWarnings("unchecked")
        Class<Map<String, Object>> clazz = (Class<Map<String, Object>>) (Class<?>) Map.class;
        return sqlManager.pageQuery(sqlId, clazz, paras, pageRequest);
    }

    /**
     * 查询第一条数据，没查到返回 null
     */
    public Map<String, Object> getMap(String sqlId, Map<String, Object> paras) {
        SqlId sql = SqlId.of(sqlId);
        @SuppressWarnings("unchecked")
        Class<Map<String, Object>> clazz = (Class<Map<String, Object>>) (Class<?>) Map.class;
        return sqlManager.selectSingle(sql, paras, clazz);
    }

    public List<Map<String, Object>> searchBySql(String sql, Map<String, Object> paras) {
        @SuppressWarnings({"unchecked"})
        Class<Map<String, Object>> clazz = (Class<Map<String, Object>>) (Class<?>) Map.class;
        return sqlManager.execute(sql, clazz, paras);
    }

}
